package com.test.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.order.entity.Order;
import com.test.order.feign.AccountService;
import com.test.order.mapper.OrderMapper;
import com.test.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final OrderMapper orderMapper;

    private final AccountService accountService;

    @Override
    @GlobalTransactional
    public Order create(String userId, String commodityCode, Integer orderCount) {
        Integer orderMoney = calculate(commodityCode, orderCount);

        accountService.debit(userId, orderMoney);

        Order order = new Order()
                .setUserId(userId)
                .setCommodityCode(commodityCode)
                .setCount(orderCount)
                .setMoney(orderMoney);

        // INSERT INTO orders ...
        int orderId = orderMapper.insert(order);
        return orderMapper.selectById(orderId);
    }

    private Integer calculate(String commodityCode, int orderCount) {
        // 根据commodityCode查询单价，假设商品单价为5
        return 5 * orderCount;
    }


}
